/**
 * 
 */
package uk.ac.lkl.common.ui;

//import java.awt.LayoutManager;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Window;
import java.awt.Container;

import javax.swing.JPanel;
import javax.swing.JComponent;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JDialog;

/**
 * @author yish
 *
 */
public class SlidePanel extends JPanel {
	private static final long serialVersionUID = 1L;

	private static final String     OPEN_MARKER  = ">> ";
	private static final String     CLOSE_MARKER = "\u25BC ";

	protected JButton    selector;
	protected JComponent payload;
	private boolean    open;
	private JLabel     status = new JLabel(OPEN_MARKER);
	

	/**
	 * 
	 */
	public SlidePanel() {
		super (new BorderLayout());
		selector = new JButton();
		selector.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
		selector.add(status);
		add(selector, BorderLayout.NORTH);
		selector.addActionListener(new ActionListener (){
			public void actionPerformed(ActionEvent e){
				toggleOpen();
			}
		});
	}
	
	public SlidePanel(String selectorText, JComponent payload){
		this(new JLabel(selectorText), payload, false);
	}
	
	public SlidePanel(String selectorText, JComponent payload, boolean open){
		this(new JLabel(selectorText), payload, open);
	}
	
	public SlidePanel(JComponent selector, JComponent payload, boolean open){
		this (payload);
		if (selector != null) this.selector.add(selector);
		this.open    = open;
		if (open) open();
	}
	
	public SlidePanel(JComponent payload){
		this();
		setPayload(payload);
	}
	
	protected void setPayload(JComponent payload){
		this.payload = payload;
		if (payload == null) return;
		payload.setVisible(false);
		add(payload, BorderLayout.CENTER);
		refresh();
	}
	
	public void toggleOpen() {
		if (open) {
			close();
		} else {
			open();
		}
	}
	
	public void open(){
		if (open) return;
		status.setText(CLOSE_MARKER);
		payload.setVisible(true);
		packPop();
		open = true;
	}
	
	public void close(){
		if (!open) return;
		status.setText(OPEN_MARKER);
		payload.setVisible(false);
		packPop();
		open = false;
		
	}
	
	protected void refresh() {
		if (open) {
			packPop();
			payload.setVisible(true);
		}		
	}
	private void packPop() {
		Container pop = getTopLevelAncestor();
		if (pop != null && Window.class.isInstance(pop)) {
			
			((Window)pop).pack();
		}
	}
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JDialog jd = new JDialog();
		jd.setLayout(new BorderLayout());
		jd.add(new SlidePanel("beans",new JButton("eat beans")), BorderLayout.NORTH);
		jd.add(new SlidePanel("beef",new JButton("eat beef")), BorderLayout.SOUTH);
		jd.pack();
		jd.setVisible(true);

	}

}
